export default {
  data () {
    return {
      // 点击单元格后，正在输入的input索引
      inputIndex: -1,

      // 选中tbody里某一行tr的索引
      rowIndex: -1,
    }
  },
  beforeDestroy () {
    this.unbindArrowKeyEvent()
  },
  mounted () {
    this.bindArrowKeyEvent()
  },
  methods: {
    eventHandler (e) {
      const { key, keyCode } = e
      if (keyCode < 37 || keyCode > 40 || key.indexOf('Arrow') === -1) {
        return false
      }
      const inputs = document.querySelectorAll('.input-cell input')
      let inputIndex = this.inputIndex
      // TODO
      const length = inputs.length
      // ArrowUp
      if (key === 'ArrowUp' || keyCode === 38) {
        inputIndex -= length
      }
      // ArrowDown
      if (key === 'ArrowDown' || keyCode === 40) {
        inputIndex += length
      }
      // ArrowLeft
      if (key === 'ArrowLeft' || keyCode === 37) {
        inputIndex--
      }
      // ArrowRight
      if (key === 'ArrowRight' || keyCode === 39) {
        inputIndex++
      }
      if (inputIndex >= 0 && inputIndex <= inputs.length - 1) {
        this.inputIndex = inputIndex
      }
      inputs[this.inputIndex] && inputs[this.inputIndex].click()
      inputs[this.inputIndex] && inputs[this.inputIndex].scrollIntoView(false)
    },

    // 绑定方向快捷键事件
    bindArrowKeyEvent () {
      document.addEventListener('keyup', this.eventHandler, false)
    },

    // 解除绑定方向快捷键事件
    unbindArrowKeyEvent () {
      document.removeEventListener('keyup', this.eventHandler, false)
    },
  }
}
